<?php

namespace app\api\controller\xiluhouse;

use app\common\controller\Api;
use app\common\model\xiluhouse\Area;
use app\common\model\Attachment;
use app\common\model\xiluhouse\HouseTagType;
use app\common\model\xiluhouse\RentalMode;
use app\common\model\xiluhouse\RentalType;
use app\common\model\xiluhouse\UserProfile;
use app\common\model\xiluhouse\Version;
use app\common\model\xiluhouse\Village;
use app\common\model\xiluhouse\VillageApply;
use app\common\model\xiluhouse\VillageBroker;
use fast\Random;
use OSS\OssClient;
use think\Config;

/**
 * @title 公共接口
 */
class Common extends Api
{
    protected $noNeedLogin = ['init_config', 'check_version','villages','rental_tags'];
    protected $noNeedRight = '*';

    /**
     * @title 加载初始化获取基本配置信息
     * @return string   $cdn_url   -    图片资源域名
     * @return string   $platform_contact_tel   -    平台热线电话
     * @return string   $app_logo   -    logo图
     * @return string   $about_article   -    关于我们
     * @return string   $agreement_article   -    隐私政策
     * @return string   $userrule_article   -    用户协议
     * @return string   $service_article   -    服务声明
     * @return string   $coupon_img   -    领券中心图片
     * @return string   $coupon_end_time   -    领券中心截止时间
     * @return string   $withdraw_rule   -    提现规则
     * @return bool     $is_ios_audit   -    是否是正在审核的ios版本
     * @return int      $init_sign_score   -    默认最初签到获得积分
     * @return string   $share_image   -  邀请图
     * @return string   $house_trend_image   -  楼房动态图
     * @return string   $helpyou_image   -  帮你找房图
     * @return string   $complain_image   -  意见反馈图
     * @return string   $app_advert   -  进入APP时的广告图
     * @return int   $service_user_id   -  配置客服
     * 
     */
    public function init_config()
    {
        $model = new \app\common\model\xiluhouse\Article;
        $about_article = $model->find(7);
        $agreement_article = $model->find(5);
        $userrule_article = $model->find(45);
        $service_article = $model->find(19);
        $audit_ios_version = \app\common\model\xiluhouse\Config::getdatas('audit_ios_version');
        $audit_ios_version_arr = [];
        $is_ios_audit = false;
        if ($audit_ios_version) {
            $platform = $this->request->server('HTTP_PLATFORM', 'android');
            //获取app版本 必要时提示版本信息不对(一般客户要求强制更新时使用)
            $version = $this->request->server('HTTP_VERSION', '');
            $audit_ios_version_arr = explode(',', $audit_ios_version);
            $is_ios_audit = ($platform == 'ios' && in_array($version, $audit_ios_version_arr)) ? true : false;
        }
        $data = [
            'cdn_url' => config('upload.cdnurl'),
            'platform_contact_tel' => \app\common\model\xiluhouse\Config::getdatas('platform_contact_tel'),
            'app_logo' => cdnurl(\app\common\model\xiluhouse\Config::getdatas('app_logo'),true),
            'is_ios_audit' => $is_ios_audit,
            'about_article' => $about_article,
            'service_article' => $service_article,
            'agreement_article' => $agreement_article,
            'userrule_article' => $userrule_article,
            'coupon_img' => cdnurl(\app\common\model\xiluhouse\Config::getdatas('coupon_img'),true),
            'coupon_end_time' => \app\common\model\xiluhouse\Config::getdatas('coupon_end_time'),
            'withdraw_rule' => \app\common\model\xiluhouse\Config::getdatas('withdraw_rule'),
            'init_sign_score' => \app\common\model\xiluhouse\Config::getdatas('init_sign_score'),
            'share_image' => cdnurl(\app\common\model\xiluhouse\Config::getdatas('share_image'),true),
            'house_trend_image' => cdnurl(\app\common\model\xiluhouse\Config::getdatas('house_trend_image'),true),
            'helpyou_image' => cdnurl(\app\common\model\xiluhouse\Config::getdatas('helpyou_image'),true),
            'complain_image' => cdnurl(\app\common\model\xiluhouse\Config::getdatas('complain_image'),true),
            'app_advert' => cdnurl(\app\common\model\xiluhouse\Config::getdatas('app_advert'),true),
            'app_advert_sec' => \app\common\model\xiluhouse\Config::getdatas('app_advert_sec'),
            'service_user_id' => \app\common\model\xiluhouse\Config::getdatas('service_user_id'),
            'kefu_pic' => cdnurl(\app\common\model\xiluhouse\Config::getdatas('kefu_pic'),true),
        ];

        if(config('site.auto_reply_switch')){
            $data['auto_reply_content'] = config('site.auto_reply_content');
        }


        $this->success('', $data);
    }

    /**
     *  @title 检测新版本
     *
     * @param string $version 版本号 x.x.x
     * @param string $platform 平台 android、ios、wx
     * @return int   $enforce   -    是否强制更新:0=否,1=是
     */
    public function check_version()
    {
        $param = $this->request->only(['version', 'platform']);
        $data  = Version::check($param['version'], $param['platform']);
        if ($data) {
            $this->success('有新版本', $data);
        } else {
            $this->error('当前为最新版本');
        }
    }

    /**
     * @title 上传文件(上传到oss)
     * @ApiMethod (POST)
     * @param File $file 文件流
     */
    public function upload()
    {
        $file = $this->request->file('file');
        $base64file=$this->request->post('basedata','');
        if (empty($file)&&empty($base64file)) {
            $this->error(__('No file upload or server upload limit exceeded'));
        }
        $upload = new \app\common\library\xiluhouse\Upload();
        $ret = $upload->upload($file,$base64file);
        if (!$ret) {
            $this->error($upload->getError());
        }
        $this->success("上传成功", $ret);
    }

    /**小程序二维码图片上传
     * @param $filePath
     * @param $fileData
     * @return bool
     */
    public static function uploadAlioss($filePath, $fileData) {
        if(!get_addon_info('alioss') || get_addon_info('alioss')['state'] != 1)  return true;
        $config = get_addon_config('alioss');
        $accessKeyId = $config['accessKeyId'];
        $accessKeySecret = $config['accessKeySecret'];
        $endpoint = $config['endpoint'];
        $bucket = $config['bucket'];
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        $ossClient->putObject($bucket, ltrim($filePath, '/'),$fileData);
        return true;
    }

    /**
     * 添加代理小区时的小区
     */
    public function villages()
    {
        $city = $this->request->param('city/s', '上海市');
        //$region = $this->request->param('region/s', '静安区');
        $map['city'] = ['like', $city . '%'];
        //$map['region'] = ['like', $region . '%'];
        if($q = $this->request->param('q/s','')){
            $map['name'] = ['like',"%$q%"];
        }

        $lat = floatval($this->request->param('lat/s', '31.235929042252'));
        $lng = floatval($this->request->param('lng/s', '121.48053886018'));

        $field = '(ACOS(SIN((' . $lat . '*3.1415)/180)*SIN((lat*3.1415)/180)+COS((' . $lat . '*3.1415)/180)*COS((lat*3.1415)/180)*COS((' . $lng . '*3.1415)/180-(lng*3.1415)/180))*6380) distance';

        #排除用户已拥有的
        if($this->auth->isLogin() && UserProfile::where('user_id',$this->auth->id)->value('is_broker') == 2){
            $village_ids = VillageBroker::where('broker_user_id',$this->auth->id)->column('village_id');
            if($village_ids){
                $map['id'] = ['not in',implode(',',$village_ids)];
            }
        }
        $lists = Village::field('id,name,check_status,prov,city,region,street,addr,'.$field)
            ->where('status','normal')
            ->where('check_status','neq',2)
            ->where($map)
            ->order("distance asc")
            ->paginate();
        if($this->auth->isLogin()){
            //$ids = array_column(collection($items)->toArray(),'id');
            $village_applys = VillageApply::where('broker_user_id',$this->auth->id)->where('check_status',0)->column('village_id');
            $village_applys = $village_applys?implode(',',$village_applys):'';
            $applys = explode(',',$village_applys);
        }
        $village_ids = $this->request->param('village_ids','');
        foreach ($lists as $row){
            $row->apply_status = 0;//未申请
            if(isset($applys) && in_array($row->id,$applys)){
                $row->apply_status = 1; //申请中
            }
            $row->distance = sprintf("%.2f",$row->distance);
            $row->checked = 0;
            if($village_ids && in_array($row->id,explode(',',$village_ids))){
                $row->checked = 1;
            }
        }
        $this->success('',$lists);
    }

    /**
     * 房源类型
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function house_type(){
        //类型
        $house_type = \app\common\model\xiluhouse\HouseType::where('status','normal')->orderRaw('weigh desc,id desc')->select();
        $this->success('查询成功', $house_type);
    }

    public function developer(){
        //类型
        $house_type = \app\common\model\xiluhouse\HouseDeveloper::where('status','normal')->orderRaw('weigh desc,id desc')->select();
        $this->success('查询成功', $house_type);
    }

    public function house_tag(){
        //类型
        $house_type = \app\common\model\xiluhouse\HouseTag::where('status','normal')
            ->where('classify',1)
            ->orderRaw('weigh desc,id desc')->select();
        $this->success('查询成功', $house_type);
    }


    /**
     * 获取房源标签
     */
    public function rental_tags()
    {

        $lists = HouseTagType::with(['tags'=>function($query){
            $query->where('status','normal')->field(['id','tag_type_id','name']);
        }])
            ->field(['id','name','multi_status'])
            ->where('status','normal')
            ->order('weigh','desc')
            ->select();

        $this->success('查询成功',$lists);
    }


    /**
     * 获取租赁模式
     */
    public function rental_mode()
    {
        $lists = RentalMode::field(['id','name'])
            ->where('status','normal')
            ->order('weigh','desc')
            ->select();
        $this->success('查询成功',$lists);
    }

    /**
     * 获取押金类型
     */
    public function rental_type()
    {
        $lists = RentalType::field(['id','name'])
            ->where('status','normal')
            ->order('weigh','desc')
            ->select();
        $this->success('查询成功',$lists);
    }

    /**
     * 设置经纪人体验账号
     */
    public function test_account_login(){
        $user_id = 14;
        $user = \app\common\model\User::get(['id'=>$user_id]);
        if(!$user){
            $this->error('体验账号已不存在');
        }
        $this->auth->direct($user->id);

        $this->success('登录成功',['userinfo' => $this->auth->getUserinfo()]);
    }
}
